// src/stores/useAuth.ts
import { ref, computed } from 'vue';

const accessToken = ref<string | null>(null);
const refreshToken = ref<string | null>(null);

export function useAuth() {
  const isAuthenticated = computed(() => !!accessToken.value);

  function setTokens(access: string, refresh?: string) {
    accessToken.value = access;
    refreshToken.value = refresh || null;
    sessionStorage.setItem('access_token', access);
    if (refresh) sessionStorage.setItem('refresh_token', refresh);
  }

  function clear() {
    accessToken.value = null;
    refreshToken.value = null;
    sessionStorage.removeItem('access_token');
    sessionStorage.removeItem('refresh_token');
  }

  function initFromStorage() {
    const at = sessionStorage.getItem('access_token');
    const rt = sessionStorage.getItem('refresh_token');
    if (at) accessToken.value = at;
    if (rt) refreshToken.value = rt;
  }

  initFromStorage();

  return {
    accessToken,
    refreshToken,
    isAuthenticated,
    setTokens,
    clear,
    initFromStorage
  };
}
